<template>
  <Page title="听后选择">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">听后选择</span>
        </div>
        <div class="nav-bar-btns flex" style="margin-left: auto">
          <div class="item flex items-center" @click="goToNextQuestion">
            <span class="name text-white">下一题</span>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full p-20px box-border overflow-hidden bg-white flex flex-col"
        >
          <div class="w-full h-full overflow-scroll">
            <!-- 概况 -->
            <div class="overview text-center">
              <div class="text-333 font-normal">
                <span>总得分：</span>
                <span
                  class="font-semibold"
                  :class="`text-${getScoreClass(score / totalScore)}`"
                  style="font-size: 0.5rem; line-height: 0.7rem"
                  >{{ score }}</span
                >
                <span :class="`text-${getScoreClass(score / totalScore)}`">分</span>
                <span>/{{ totalScore }}分</span>
              </div>
            </div>
            <!-- 详情 -->
            <div class="questions-wrap mt-10px">
              <div v-for="(i, index) in questions" :key="i.questionId" class="item">
                <div v-for="(question, question_index) in i.children" :key="question_index">
                  <Stem
                    master="exercise_record_english"
                    :data="question.stem"
                    :answer="question.answer"
                    :student-answer="question.studentAnswer"
                    :readonly="true"
                  />
                  <div class="hr my-30px" v-show="question_index < i.children.length - 1"></div>
                </div>
                <div class="hr my-30px" v-show="index < questions.length - 1"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import Stem from '@/components/question/stem'
import { mapState } from 'vuex'
import { formatQuestionStem } from '@/utils/question'
import Mixin from '../mixin'
import { getEnglishPracticeApi, getNextEnglishQuestionApi } from '@/api/exercise'

export default {
  components: {
    Page,
    Stem
  },
  mixins: [Mixin],
  inject: ['_addTagClickHandler', '_removeTagClickHandler'],
  data() {
    return {}
  },
  computed: {
    ...mapState(['exerciseCenter']),
    questions() {
      const { questions } = this.exerciseCenter.currentPractice

      return questions
        .map((question, question_index) => {
          const startIndex = question_index + (question_index + 1)
          const { questionDto } = question

          if (!questionDto) return null

          const {
            stem: { structure_type }
          } = questionDto

          if (structure_type === 'collector.choose') {
            const {
              questionIds,
              stem: {
                info: { question: stemQuestions }
              },
              remoteStudentAnswer
            } = questionDto

            let totalStudentScore = 0,
              totalQuestionScore = 0
            return {
              children: questionIds.map((id, index) => {
                const q = stemQuestions.find((sq) => sq.questionId === id)
                const { questionId } = q
                const stem = JSON.parse(q.stem)
                const {
                  info: { audio: audioSrc }
                } = stem
                const answer = JSON.parse(q.answer)

                const { studentScore, questionScore, studentAnswer } = remoteStudentAnswer[index]
                totalStudentScore += studentScore
                totalQuestionScore += questionScore
                const templateSpeaker = `<span class="append-speaker"><img src="static/icons/speaker.png" data-question-id="${questionId}" data-audio-src="${audioSrc}" /></span>`
                const {
                  info: { st_nr, xtlist = [] }
                } = stem

                let sqs = []
                xtlist.forEach((i, index) => {
                  const { xt_nr = '', xxlist = [] } = i
                  const templateQuestion = xt_nr.replace(/ets_th[0-9]\s/, `${startIndex + index}.`)
                  let templateScore = `<span class="text-FF4040">（未作答）</span>`
                  try {
                    const { anSqs } = studentAnswer
                    const anStudent = anSqs[index].ans[0].anStudent
                    const score = anSqs[index].ans[0].studentScore
                    const totalScore = anSqs[index].ans[0].questionScore
                    templateScore = `<span class="text-${this.getScoreClass(
                      score / totalScore
                    )}">（得分：${anStudent ? `${score}分` : '未作答'}/${totalScore}分）</span>`
                  } catch (error) {}
                  const html = `<div class="mt-${
                    index === 0 ? 10 : 18
                  }px">${templateQuestion}${templateScore}</div>`
                  sqs.push({
                    html,
                    og: {
                      ogOps: xxlist.map((item, index) => {
                        const { xx_mc, xx_nr } = item

                        return {
                          index: xx_mc,
                          html: `${xx_mc}.${xx_nr}`
                        }
                      }),
                      cols: xxlist.length
                    },
                    sqs: [],
                    type: '选择题'
                  })
                })

                return {
                  questionId,
                  stem: formatQuestionStem({
                    html: `<div><p><span>听下面一段对话，回答第${startIndex}至第${
                      startIndex + 1
                    }小题。现在，你有10秒钟的时间阅读这两道小题。</span>${templateSpeaker}</p><p>${st_nr}</p></div>`,
                    og: null,
                    sqs,
                    type: '英语听说-听后选择'
                  }),
                  answer,
                  studentAnswer
                }
              }),
              totalStudentScore,
              totalQuestionScore
            }
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    score() {
      let score = 0
      this.questions.forEach((q) => {
        const { totalStudentScore } = q
        score += totalStudentScore
      })

      return score
    },
    totalScore() {
      let totalScore = 0
      this.questions.forEach((q) => {
        const { totalQuestionScore } = q
        totalScore += totalQuestionScore
      })

      return totalScore
    }
  },
  mounted() {
    this._addTagClickHandler('img', this.handleImgClick)
    console.log(this.questions)
  },
  beforeDestroy() {
    this._removeTagClickHandler('img', this.handleImgClick)
  },
  methods: {
    back() {
      this.$router.back()
    },
    handleImgClick(node) {
      const { currentSrc = '' } = node
      if (currentSrc.indexOf('speaker.png') != -1) {
        const { audioSrc } = node.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          this.$message.error('未作答')
          return
        }

        this.playAudio(node, audioSrc)
      }
    },
    async goToNextQuestion() {
      const {
        record: { courseId, difficultyLevel, questionTypeId },
        questions
      } = this.exerciseCenter.currentPractice
      const questionId =
        Array.isArray(questions) && questions.length > 0 ? questions[0].questionId : undefined

      // 加载动画
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内加载不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)

      const { data: record } = await getEnglishPracticeApi({
        courseId,
        difficultyLevel,
        questionTypeId
      })
      const { data: question, msg } = await getNextEnglishQuestionApi({
        questionId,
        courseId,
        difficultyLevel,
        questionTypeId,
        kpointPracticeId: record.id
      })

      // 关闭加载动画
      clearTimeout(timer)
      loading.close()

      if (!question) {
        this.$message.error(msg)
      } else {
        this.$store.commit('setCurrentPractice', {
          record: Object.assign(record, { kpointIds: [record.kpointId] }),
          questions: [question],
          questionIndex: 0
        })

        this.$router.replace('/pages/exercise/practice/english/index').then(() => {
          this.$store.commit('setCurrentPractice', {
            record: Object.assign(record, { kpointIds: [record.kpointId] }),
            questions: [question],
            questionIndex: 0
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.nav-bar-btns {
  .item {
    height: 30px;
    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {
  border-radius: 16px;

  .overview {
    font-size: 20px;
  }

  .questions-wrap {
    .item {
      /deep/ .append-speaker {
        display: inline-block;
        width: 46px;
        height: 46px;
        position: relative;

        img {
          width: 46px;
          height: 46px;
          position: absolute;
          top: 50%;
          transform: translateY(-24%);
        }

        .playing {
          @keyframes play {
            0% {
              opacity: 0.5;
            }

            25% {
              opacity: 0.25;
            }

            50% {
              opacity: 0.5;
            }

            75% {
              opacity: 0.75;
            }

            100% {
              opacity: 1;
            }
          }

          animation: play 1s ease-in-out infinite backwards;
        }
      }

      .hr {
        height: 1px;
        background: #eee;
      }
    }
  }
}
</style>
